package com.company.project.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.common.utils.*;
import com.company.project.entity.*;
import com.company.project.mapper.*;
import com.company.project.service.*;
import com.company.project.vo.req.TSeatsEntityOperationReqVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Service("yhCallService")
@Slf4j
public class YhCallServiceImpl implements YhCallService {
    @Autowired
    public TSeatsMapper tSeatsMapper;
    @Autowired
    public TXiaohaoMapper xiaohaoMapper;
    @Resource
    private UserService userService;
    @Resource
    private HttpSessionService httpSessionService;
    @Resource
    private TZjhmglMapper zjhmglMapper;
    @Autowired
    private TCallbakMapper callbakMapper;
    @Autowired
    private TThjlmxMapper thjlmxMapper;
    @Autowired
    public TThrbMapper thrbMapper;
    @Override
    public DataResult outbound(TSeatsEntityOperationReqVO vo) {
        try {
            //根据登录人查询 主叫号码、中间号
            String userId = httpSessionService.getCurrentUserId();
            SysUser sysUser = userService.getById(userId);
            TSeatsEntity tSeats = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getAccountid, userId));
            TSeatsEntity gsgl = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery().eq(TSeatsEntity::getCorporatename, tSeats.getCorporatename())
                    .eq(TSeatsEntity::getGsgl, "1"));
            Integer residue = gsgl.getResidue();
            String seats = tSeats.getState(); //状态  启用|禁用
            if(Func.equals("1",seats)) return DataResult.fail("外呼失败，账号已禁用请联系管理人员！");
            if (residue < 1) return DataResult.fail("外呼失败，剩余次数不足！");
            if (Func.isEmpty(gsgl)) return DataResult.fail("外呼失败，线路为空！");
            String line = gsgl.getLine();//线路
            //被叫号码
            String phoneWH = vo.getPhoneWH();
            log.info("外呼开始！！！！");
            log.info("线路："+line);

            if (Func.isEmpty(line)) return DataResult.fail("外呼失败，线路为空！");
            /**
             * 线路1 移动线路
             * 通过中间号呼叫
             */
            if (Func.equals("有销移动",line)) {
                //主叫号码
                TZjhmglEntity tZjhmglEntity = zjhmglMapper.selectOne(Wrappers.<TZjhmglEntity>lambdaQuery()
                        .eq(TZjhmglEntity::getUserid, sysUser.getUsername())
                        .eq(TZjhmglEntity::getStart, "1"));
                if (Func.isEmpty(tZjhmglEntity)) return DataResult.fail("外呼失败，主叫号码为空！");
                String phone = tZjhmglEntity.getZjhm();
                log.info("主叫号码："+phone);

                //获取管理坐席的小号
                TSeatsEntity glzx = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                        .eq(TSeatsEntity::getCorporatename, tSeats.getCorporatename())
                        .eq(TSeatsEntity::getGsgl,"1")
                );

                //小号 非禁用 剩余次数小的
                TXiaohaoEntity tXiaohaoEntity = xiaohaoMapper.selectOneShengyucishu(glzx.getId());
                if (Func.isEmpty(tXiaohaoEntity)) return DataResult.fail("外呼失败，中间号没有剩余次数！");
                //中间号
                String xiaohao = tXiaohaoEntity.getXiaohao();
                log.info("中间号："+xiaohao);
                log.info("被叫号码："+phoneWH);
                if (phoneWH.indexOf("-") > -1) {
                    phoneWH = phoneWH.replace("-", "");
                }
                HttpResponse bind = YdCall.bind(phone, phoneWH, xiaohao, "/index/callbak/dxline");
                JSONObject body = JSONUtil.parseObj(bind.body());
                log.info("外呼有销移动线路返回结果： "+body.getStr("msg")+";  状态码："+body.containsKey("code"));
                log.info("外呼有销移动线路返回结果--data： "+body.getStr("data"));
                if (!body.containsKey("code") || !"200".equals(body.getStr("code"))) {
                    log.info("外呼失败    返回结果： "+body.getStr("msg")+";  状态码："+body.containsKey("code"));
                    return DataResult.fail(body.getStr("msg"));
                }
                //外呼返回参数
                String sessionId = JSONUtil.parseObj(body.get("data")).getStr("sessionId");//绑定唯一 ID
                String bindNbr = JSONUtil.parseObj(body.get("data")).getStr("bindNbr");//中间号
                log.info("外呼返回参数  绑定唯一 ID： "+sessionId+";  中间号："+bindNbr);

                TCallbakEntity callbak = new TCallbakEntity();
                callbak.setBindId(sessionId);//绑定 ID
                callbak.setZjhm(bindNbr);//中间号
                callbak.setUserid(tSeats.getId());//创建人 坐席 人
                callbakMapper.insert(callbak);
                TThjlmxEntity tThjlmxEntity = new TThjlmxEntity();
                tThjlmxEntity.setBindId(sessionId);
                tThjlmxEntity.setCtime(new Date());
                tThjlmxEntity.setYgxm(sysUser.getUsername());
                thjlmxMapper.insert(tThjlmxEntity);
                return DataResult.success(body.getStr("msg"));//提示不对

            } else if (Func.equals("有销电信",line)) {
                //主叫号码
                TZjhmglEntity tZjhmglEntity = zjhmglMapper.selectOne(Wrappers.<TZjhmglEntity>lambdaQuery()
                        .eq(TZjhmglEntity::getUserid, sysUser.getUsername())
                        .eq(TZjhmglEntity::getStart, "1"));
                if (Func.isEmpty(tZjhmglEntity)) return DataResult.fail("外呼失败，主叫号码为空！");
                String phone = tZjhmglEntity.getZjhm();
                log.info("主叫号码："+phone);

                //获取管理坐席的小号
                TSeatsEntity glzx = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                        .eq(TSeatsEntity::getCorporatename, tSeats.getCorporatename())
                        .eq(TSeatsEntity::getGsgl,"1")
                );

                //小号 非禁用 剩余次数小的
//                TXiaohaoEntity tXiaohaoEntity = xiaohaoMapper.selectOneShengyucishu(glzx.getId());
//                if (Func.isEmpty(tXiaohaoEntity)) return DataResult.fail("外呼失败，中间号没有剩余次数！");
                //中间号
                String xiaohao = phone;
                log.info("中间号："+xiaohao);
                log.info("被叫号码："+phoneWH);
                if (phoneWH.indexOf("-") > -1) {
                    phoneWH = phoneWH.replace("-", "");
                }
                HttpResponse bind = YdCall.bind(phone, phoneWH, xiaohao, "/index/callbak/dxline");
                JSONObject body = JSONUtil.parseObj(bind.body());
                log.info("外呼有销移动线路返回结果： "+body.getStr("msg")+";  状态码："+body.containsKey("code"));
                log.info("外呼有销移动线路返回结果--data： "+body.getStr("data"));
                if (!body.containsKey("code") || !"200".equals(body.getStr("code"))) {
                    log.info("外呼失败    返回结果： "+body.getStr("msg")+";  状态码："+body.containsKey("code"));
                    return DataResult.fail(body.getStr("msg"));
                }
                //外呼返回参数
                String sessionId = JSONUtil.parseObj(body.get("data")).getStr("sessionId");//绑定唯一 ID
                String bindNbr = JSONUtil.parseObj(body.get("data")).getStr("bindNbr");//中间号
                log.info("外呼返回参数  绑定唯一 ID： "+sessionId+";  中间号："+bindNbr);

                TCallbakEntity callbak = new TCallbakEntity();
                callbak.setBindId(sessionId);//绑定 ID
                callbak.setZjhm(bindNbr);//中间号
                callbak.setUserid(tSeats.getId());//创建人 坐席 人
                callbak.setCalltime(new Date());
                callbakMapper.insert(callbak);
                TThjlmxEntity tThjlmxEntity = new TThjlmxEntity();
                tThjlmxEntity.setBindId(sessionId);
                tThjlmxEntity.setCtime(new Date());
                tThjlmxEntity.setYgxm(sysUser.getUsername());
                tThjlmxEntity.setOrg(tSeats.getDept());
                tThjlmxEntity.setZjhm(phone);//主叫号码
                tThjlmxEntity.setBjhm(phoneWH); //被叫号码
                tThjlmxEntity.setHdstart("3"); //回调状态
                log.info("165 记录通话明细:{}", tThjlmxEntity.toString());
                thjlmxMapper.insert(tThjlmxEntity);
                return DataResult.success(body.getStr("msg"));//提示不对

            } else if (Func.equals("多方移动",line) || Func.equals("多方电信",line)) {
                //主叫号码
                TZjhmglEntity tZjhmglEntity = zjhmglMapper.selectOne(Wrappers.<TZjhmglEntity>lambdaQuery()
                        .eq(TZjhmglEntity::getUserid, sysUser.getUsername())
                        .eq(TZjhmglEntity::getStart, "1"));
                if (Func.isEmpty(tZjhmglEntity)) return DataResult.fail("外呼失败，主叫号码为空！");
                String phone = tZjhmglEntity.getZjhm();
                log.info("主叫号码："+phone);
                //中间号
                String xiaohao = tSeats.getPhone(); ;
                if (Func.equals("多方移动",line)) {
                    //获取管理坐席的小号
                    TSeatsEntity glzx = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                            .eq(TSeatsEntity::getCorporatename, tSeats.getCorporatename())
                            .eq(TSeatsEntity::getGsgl,"1")
                    );

                    //小号 非禁用 剩余次数小的
                    TXiaohaoEntity tXiaohaoEntity = xiaohaoMapper.selectOneShengyucishu(glzx.getId());
                    if (Func.isEmpty(tXiaohaoEntity)) return DataResult.fail("外呼失败，中间号没有剩余次数！");
                    //中间号
                    xiaohao = tXiaohaoEntity.getXiaohao();
                }

                log.info("中间号："+xiaohao);
                log.info("被叫号码："+phoneWH);
                if (phoneWH.indexOf("-") > -1) {
                    phoneWH = phoneWH.replace("-", "");
                }
                HttpResponse bind = YdSzcCall.bind(phone, phoneWH, xiaohao, "/index/callbak/dyline");
                JSONObject body = JSONUtil.parseObj(bind.body());
                log.info("外呼多云移动线路返回结果： "+body.getStr("message")+";  状态码："+body.getStr("code"));
                log.info("外呼多云移动线路返回结果--data： "+body.getStr("data"));
                if (!body.containsKey("code") || !"0000".equals(body.getStr("code"))) {
                    log.info("外呼失败    返回结果： "+body.getStr("message")+";  状态码："+body.getStr("code"));
                    return DataResult.fail(body.getStr("message"));
                }
                //外呼返回参数
                String sessionId = JSONUtil.parseObj(body.get("data")).getStr("bindId");//绑定唯一 ID
                String bindNbr = JSONUtil.parseObj(body.get("data")).getStr("telX");//中间号
                log.info("外呼返回参数  绑定唯一 ID： "+sessionId+";  中间号："+bindNbr);

                TCallbakEntity callbak = new TCallbakEntity();
                callbak.setBindId(sessionId);//绑定 ID
                callbak.setZjhm(xiaohao);//中间号
                callbak.setUserid(tSeats.getId());//创建人 坐席 人
                callbak.setCalltime(new Date());
                callbakMapper.insert(callbak);
                TThjlmxEntity tThjlmxEntity = new TThjlmxEntity();
                tThjlmxEntity.setBindId(sessionId);
                tThjlmxEntity.setCtime(new Date());
                tThjlmxEntity.setYgxm(sysUser.getUsername());
                tThjlmxEntity.setOrg(tSeats.getDept());
                tThjlmxEntity.setZjhm(phone);//主叫号码
                tThjlmxEntity.setBjhm(phoneWH); //被叫号码
                tThjlmxEntity.setHdstart("3"); //回调状态
                log.info("1088 记录通话明细:{}", tThjlmxEntity.toString());
                thjlmxMapper.insert(tThjlmxEntity);
                return DataResult.success(body.getStr("message"));//提示不对
            } else if (Func.equals("连连移动",line) || Func.equals("连连电信",line)) {
                //主叫号码
                TZjhmglEntity tZjhmglEntity = zjhmglMapper.selectOne(Wrappers.<TZjhmglEntity>lambdaQuery()
                        .eq(TZjhmglEntity::getUserid, sysUser.getUsername())
                        .eq(TZjhmglEntity::getStart, "1"));
                if (Func.isEmpty(tZjhmglEntity)) return DataResult.fail("外呼失败，主叫号码为空！");
                String phone = tZjhmglEntity.getZjhm();
                log.info("主叫号码："+phone);
                //中间号
                String xiaohao = phone ;
                if (Func.equals("连连移动",line)) {
                    //获取管理坐席的小号
                    TSeatsEntity glzx = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                            .eq(TSeatsEntity::getCorporatename, tSeats.getCorporatename())
                            .eq(TSeatsEntity::getGsgl,"1")
                    );

                    //小号 非禁用 剩余次数小的
                    TXiaohaoEntity tXiaohaoEntity = xiaohaoMapper.selectOneShengyucishu(glzx.getId());
                    if (Func.isEmpty(tXiaohaoEntity)) return DataResult.fail("外呼失败，中间号没有剩余次数！");
                    //中间号
                    xiaohao = tXiaohaoEntity.getXiaohao();
                }

                log.info("中间号："+xiaohao);
                log.info("被叫号码："+phoneWH);
                if (phoneWH.indexOf("-") > -1) {
                    phoneWH = phoneWH.replace("-", "");
                }
                HttpResponse bind = YdDjCall.bind(phone, phoneWH, xiaohao, "/index/callbak/dyline");
                JSONObject body = JSONUtil.parseObj(bind.body());
                log.info("外呼连连移动线路返回结果： "+body.getStr("message")+";  状态码："+body.getStr("code"));
                log.info("外呼连连移动线路返回结果--bindId： "+body.getStr("bindId"));
                if (!body.containsKey("code") || !"0".equals(body.getStr("code"))) {
                    log.info("外呼失败    返回结果： "+body.getStr("message")+";  状态码："+body.getStr("code"));
                    return DataResult.fail(body.getStr("message"));
                }
                //外呼返回参数
                String sessionId = body.getStr("bindId");//绑定唯一 ID
                String bindNbr = body.getStr("number");//中间号
                log.info("外呼连连移动返回参数  绑定唯一 ID： "+sessionId+";  中间号："+bindNbr);

                TCallbakEntity callbak = new TCallbakEntity();
                callbak.setBindId(sessionId);//绑定 ID
                callbak.setZjhm(xiaohao);//中间号
                callbak.setUserid(tSeats.getId());//创建人 坐席 人
                callbak.setCalltime(new Date());
                callbakMapper.insert(callbak);
                TThjlmxEntity tThjlmxEntity = new TThjlmxEntity();
                tThjlmxEntity.setBindId(sessionId);
                tThjlmxEntity.setCtime(new Date());
                tThjlmxEntity.setYgxm(sysUser.getUsername());
                tThjlmxEntity.setOrg(tSeats.getDept());
                tThjlmxEntity.setZjhm(phone);//主叫号码
                tThjlmxEntity.setBjhm(phoneWH); //被叫号码
                tThjlmxEntity.setHdstart("3"); //回调状态
                log.info("284 记录通话明细:{}", tThjlmxEntity.toString());
                thjlmxMapper.insert(tThjlmxEntity);
                return DataResult.success(body.getStr("message"));//提示不对
            } else if (Func.equals("好小子移动",line) || Func.equals("好小子电信",line)) {
                //主叫号码
                TZjhmglEntity tZjhmglEntity = zjhmglMapper.selectOne(Wrappers.<TZjhmglEntity>lambdaQuery()
                        .eq(TZjhmglEntity::getUserid, sysUser.getUsername())
                        .eq(TZjhmglEntity::getStart, "1"));
                if (Func.isEmpty(tZjhmglEntity)) return DataResult.fail("外呼失败，主叫号码为空！");
                String phone = tZjhmglEntity.getZjhm();
                log.info("主叫号码："+phone);
                //中间号
                String xiaohao = phone ;
                if (Func.equals("好小子移动",line)) {
                    //获取管理坐席的小号
                    TSeatsEntity glzx = tSeatsMapper.selectOne(Wrappers.<TSeatsEntity>lambdaQuery()
                            .eq(TSeatsEntity::getCorporatename, tSeats.getCorporatename())
                            .eq(TSeatsEntity::getGsgl,"1")
                    );

                    //小号 非禁用 剩余次数小的
                    TXiaohaoEntity tXiaohaoEntity = xiaohaoMapper.selectOneShengyucishu(glzx.getId());
                    if (Func.isEmpty(tXiaohaoEntity)) return DataResult.fail("外呼失败，中间号没有剩余次数！");
                    //中间号
                    xiaohao = tXiaohaoEntity.getXiaohao();
                }

                log.info("中间号："+xiaohao);
                log.info("被叫号码："+phoneWH);
                if (phoneWH.indexOf("-") > -1) {
                    phoneWH = phoneWH.replace("-", "");
                }
                HttpResponse bind = YdDnCall.bind(phone, phoneWH, xiaohao, "/index/callbak/dnline");
                JSONObject body = JSONUtil.parseObj(bind.body());
                log.info("外呼好小子 线路返回结果： "+body.getStr("message")+";  状态码："+body.getStr("code"));
                log.info("外呼 好小子 线路返回结果--bindId： "+body.getStr("bindId"));
                if (!body.containsKey("code") || !"0".equals(body.getStr("code"))) {
                    log.info("外呼失败    返回结果： "+body.getStr("msg")+";  状态码："+body.getStr("code"));
                    return DataResult.fail(body.getStr("msg"));
                }
                /**
                 * {
                 *     "code": 0,
                 *     "msg": "success",
                 *     "data": {
                 *         "bind_id": "CR2021122255555062036389",
                 *         "number": "18577888888",
                 *         "type": 1 //直拨 2回拨
                 *     }
                 * }
                 */
                Map<String,Object> objectMap = (Map)body.get("data");

                //外呼返回参数
                String sessionId = String.valueOf(objectMap.get("bind_id"));//绑定唯一 ID
                String bindNbr = String.valueOf(objectMap.get("number"));//中间号
                log.info("外呼好小子 返回参数  绑定唯一 ID： "+sessionId+";  中间号："+bindNbr);

                TCallbakEntity callbak = new TCallbakEntity();
                callbak.setBindId(sessionId);//绑定 ID
                callbak.setZjhm(xiaohao);//中间号
                callbak.setUserid(tSeats.getId());//创建人 坐席 人
                callbak.setCalltime(new Date());
                callbakMapper.insert(callbak);
                TThjlmxEntity tThjlmxEntity = new TThjlmxEntity();
                tThjlmxEntity.setBindId(sessionId);
                tThjlmxEntity.setCtime(new Date());
                tThjlmxEntity.setYgxm(sysUser.getUsername());
                tThjlmxEntity.setOrg(tSeats.getDept());
                tThjlmxEntity.setZjhm(phone);//主叫号码
                tThjlmxEntity.setBjhm(phoneWH); //被叫号码
                tThjlmxEntity.setHdstart("3"); //回调状态

                thjlmxMapper.insert(tThjlmxEntity);
                return DataResult.success("呼叫成功");//提示不对
            } else {
                return DataResult.fail("外呼失败，没有可用线路！");
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            return DataResult.fail("外呼失败，请联系管理员！");
        }
    }
}
